package ifmo.group5512.timer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created with IntelliJ IDEA.
 * User: katerina
 * Date: 31.10.12
 * Time: 23:37
 * To change this template use File | Settings | File Templates.
 */
public class UserInputProcessor implements Runnable {

    private final InputProvider inputProvider = new InputProvider();

    private int menu() {
        System.out.println("__User input__");
        System.out.println("See current configuration______________press 1");
        System.out.println("See input state (manual/modeling)______press 2");
        System.out.println("Change input state (manual/modeling)___press 3");
        System.out.println("Exit___________________________________press 4");

        int command = inputProvider.rawIntInput("Command >> ");
        while (command <= 0 || command > 4) {
            System.out.println("Incorrect input. Command is a single digit in the interval [1, 4].");
            command = inputProvider.rawIntInput("Try again >> ");
        }
        return command;
    }

    private void seeCurrentConfiguration() {
        System.out.println(CurrentManagerConfiguration.self.toString());
    }

    private void seeInputState() {
        if (CurrentManagerConfiguration.self.isManualInput()) {
            System.out.println("Input is manual from front office.");
            return;
        }
        System.out.println("Input is automatic from math module.");
    }

    private void changeInputState() {
        CurrentManagerConfiguration.self.switchInputState();
        seeInputState();
    }

    @Override
    public void run() {
        int command = -1;
        do {
            switch (command) {

                case 1: {
                    seeCurrentConfiguration();
                    break;
                }

                case 2: {
                    seeInputState();
                    break;
                }

                case 3: {
                    changeInputState();
                    break;
                }
            }

            command = menu();
        } while (command > 0 && command < 4);
    }

    private static class InputProvider {
        private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        public int rawIntInput(String comment) {
            System.out.print(comment);

            try {
                String input = reader.readLine();
                return Integer.parseInt(input);
            } catch (IOException ex) {
                return -1;
            } catch (NumberFormatException ex) {
                return -1;
            }
        }
    }
}
